package cave.ui;

import java.util.ArrayList;

import android.util.FloatMath;
import cave.game.InputEvent;
import cave.renderer.RenderList;
import cave.renderer.Sprite;
import cave.renderer.Texture;
import cave.utils.Pool;

public class Dpad implements DynamicUiItem {

	private final float BUTTON_RADIUS = 0.1f;
	
	private Sprite sprBg, sprButton;
	
	// Center coordinates
	private float x, y;
	
	// Dpad radius
	private float r;
		
	private boolean down;
	private float vecX, vecY;
	private int pointerId;
	
	public Dpad(float x, float y, float diameter, Texture texBg, Texture texButton) {
		
		sprBg = Pool.getSprite();
		sprBg.init(texBg, x, y, diameter, diameter);
				
		this.r = diameter*0.5f;
		this.x = x + r;
		this.y = y + r;
		pointerId = -1;
		
		sprButton = Pool.getSprite();
		sprButton.init(texButton, this.x - BUTTON_RADIUS, this.y - BUTTON_RADIUS, BUTTON_RADIUS*2, BUTTON_RADIUS*2);
		
	}

	@Override
	public void update(float dt, ArrayList<InputEvent> events) {
		InputEvent event;
		for (int i = 0; i < events.size(); ++i) {
			event = events.get(i);
			if (!event.isInUse()) {
				if (down && event.getPointerId() == pointerId) {
					event.setInUse(true);
					switch (event.getType()) {
					
					case UP:
						updateVec(0, 0);
						down = false;
						pointerId = -1;
						break;
						
					case MOVE:
						if (down) {
							
							float dx = event.getX() - x;
							float dy = event.getY() - y;
							float dd = dx*dx + dy*dy;
							if (dd > r*r) {
								float d = FloatMath.sqrt(dd);
								dx = dx / d * r;
								dy = dy / d * r;
							}
							
							updateVec(dx, dy);
						}
						break;
					}
				} else {
					if (event.getType() == InputEvent.Type.DOWN &&
							((x-event.getX())*(x-event.getX()) + (y-event.getY())*(y-event.getY()) <= r*r)) {
						down = true;
						pointerId = event.getPointerId();
						event.setInUse(true);
						updateVec(event.getX() - x, event.getY() - y);
					}
				}
			}
		}
	}

	@Override
	public void draw(RenderList renderList) {
		renderList.addScreenSprite(sprBg);
		renderList.addScreenSprite(sprButton);
	}

	@Override
	public void destroy() {
		sprBg.freeTextures();
		sprButton.freeTextures();
		
		Pool.free(sprBg);
		Pool.free(sprButton);
	}
	
	private void updateVec(float x, float y) {
		vecX = x;
		vecY = y;
		sprButton.setX(this.x + x - BUTTON_RADIUS);
		sprButton.setY(this.y + y - BUTTON_RADIUS);
	}
	
	public float getVecX() {
		return vecX / r;
	}
	
	public float getVecY() {
		return vecY / r;
	}
}
